// pages/order_immediately/order_immediately.js
const utils = require('../../utils/utils');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 地址
        address: {},
        // 重量
        amount: ['3-5件(2-6kg)', '6-8件(4-10kg)', '9-12件(8-12kg)', '12+件(10+kg)'],
        // 时间选择区间
        callTimeList: [
            {from: 9, to: 11, isAfter: false, timeText: '09:00-11:00'},
            {from: 11, to: 13, isAfter: false, timeText: '11:00-13:00'},
            {from: 13, to: 15, isAfter: false, timeText: '13:00-15:00'},
            {from: 15, to: 17, isAfter: false, timeText: '15:00-17:00'},
            {from: 17, to: 19, isAfter: false, timeText: '17:00-19:00'},
            {from: 19, to: 21, isAfter: false, timeText: '19:00-21:00'}
        ],
        // 重量编号
        amountIndex: 0,
        // 当前时间
        nowHour: 0,
        // 日期组件的显隐
        dateFlag: false,
        // 备注组件的显隐
        remarkFlag: false,
        // 备注字数
        wordNum: 0,
        // 备注内容
        remarkWord: '',
        // 上门时间内容
        timeWord: '点击选择时间',
        // 下单类型
        orderType: '公益赠送',
        // 本单金额
        orderMoney: 27,
        // 左边的时间选择编号
        _timeIndex: 1,
        // 右边的时间选择编号
        _hourIndex: -1
    },
    /**
     * 选择地址
     */
    onSelectAddress() {
        // 存储当前页面选择
        let placeInfo = {
            timeIndex: this.data._timeIndex,
            hourIndex: this.data._hourIndex,
            timeWord: this.data.timeWord,
            remarkNum: this.data.wordNum,
            remarkText: this.data.remarkWord
        }
        wx.setStorageSync('placeInfo', placeInfo);
        // 选择地址
        wx.navigateTo({
            url: '/pages/address_administration/address_administration',
        }).then(res => {
            console.log('address to new res ==> ', res);
        }, err => {
            console.log('address to new err ==> ', err);
        });
    },
    /**
     * 显示上门时间选择组件
     */
    onShowDate() {
        this.setData({
            dateFlag: true
        });
    },
    /**
     * 显示备注选择组件
     */
    onShowRemark() {
        this.setData({
            remarkFlag: true
        });
    },
    /**
     * 处理备注
     * @param {*} e 
     */
    changeReamrkInput(e) {
        this.setData({
            wordNum: e.detail.value.length,
            remarkWord: e.detail.value
        });
    },
    /**
     * 点击时间-左
     */
    onDateChecked(e) {
        let index = e.currentTarget.dataset.index;
        // console.log('index ==> ', e.currentTarget.dataset.index);
        this.setData({
            _timeIndex: index
        });
        this.dealCallTimeList();
    },
    /**
     * 选择时间-小时
     */
    onSelectHour(e) {
        let index = e.currentTarget.dataset.index;
        if(this.data.nowHour >=7 && this.data.nowHour < 21 && index === 99) {
            this.setData({
                _hourIndex: index,
                timeWord: '2小时内上门'
            });
        }else if(!this.data.callTimeList[index].isAfter) {
            this.setData({
                _hourIndex: index,
                timeWord: this.data.callTimeList[index].timeText
            });
        }
    },
    /**
     * 获取立即下单的选择
     */
    getPlaceInfo() {
        let placeInfo = wx.getStorageSync('placeInfo');
        if(placeInfo) {
            this.setData({
                _timeIndex: placeInfo.timeIndex,
                _hourIndex: placeInfo.hourIndex,
                timeWord: placeInfo.timeWord,
                wordNum: placeInfo.remarkNum,
                remarkWord: placeInfo.remarkText
            });
        }
    },
    /**
     * 获取回收地址
     */
    getRecycleInfo() {
        let recycleAddress = wx.getStorageSync('recycleAddress');
        let recycleType = wx.getStorageSync('recycleType');
        if(recycleAddress || recycleType) {
            this.setData({
                address: recycleAddress,
                amountIndex: recycleType.oid,
                orderType: recycleType.otype,
                orderMoney: recycleType.oMoney
            });
        }
    },
    /**
     * 处理上门时间列表
     */
    dealCallTimeList() {
        let timeList = this.data.callTimeList;
        if(this.data._timeIndex === 1) {
            let now = new Date().getHours();
            for(let i = 0; i < timeList.length; i++) {
                if(now >= timeList[i].to) {
                    timeList[i].isAfter = true;
                }else {
                    timeList[i].isAfter = false;
                }
            }
        }else {
            for(let i = 0; i < timeList.length; i++) {
                timeList[i].isAfter = false;
            }
        }
        this.setData({
            callTimeList: timeList
        });
    },
    /**
     * 获取用户预约上门时间，2小时以内
     */
    getComeTime() {
        let date = new Date();
        let time = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + (date.getDate() + this.data._timeIndex - 1)).slice(-2);
        if(this.data._hourIndex === 99){
            // 上门时间为: 2小时以内
            let h = date.getHours();
            let m = date.getMinutes();
            time += ' ' + ('0' + h).slice(-2) + ':' + ('0' + m).slice(-2) + '-' + ('0' + (h + 2)).slice(-2) + ':' + ('0' + m).slice(-2);
        }else {
            // 上门时间为其它
            time += ' ' + this.data.timeWord;
        }
        return time;
    },
    /**
     * 点击下单按钮
     */
    onPlaceOrder() {
        if(this.data._hourIndex === -1) {
            this.$showMsg('请选择上门时间');
        }else {
            let orderForm = {
                // 订单类型：公益赠送 | 立即下单
                orderType: this.data.orderType,
                // 订单联系人、地址等信息
                address: this.data.address,
                // 订单重量编号
                ammount: this.data.amountIndex,
                // 订单重量字符串
                amountStr: this.data.amount[this.data.amountIndex],
                // 订单创建时间
                createTime: new Date(),
                // 订单预约上门时间
                orderTime: this.getComeTime(),
                // 订单备注
                remark: this.data.remarkWord,
                // 订单预估价格
                estimatedPrice: this.data.orderMoney,
                // 订单编号
                orderCode: utils.orderCode(),
                // 订单状态：0-未完成 | 1-已完成
                state: 0
            }
            // 调用云函数接口，存储订单数据
            wx.cloud.callFunction({
                name: 'databaseApi',
                data: {
                    type: 'addRecycleOrder',
                    reqData: orderForm
                }
            }).then(res => {
                // 添加成功
                // console.log('addRecycleOrder success ==>', res);
                // 统计收入
                return wx.redirectTo({
                            url: '/pages/order_successful/order_successful?type=' + this.data.orderType,
                        });
            }, err => {
                // 添加失败
                console.log('addRecycleOrder fail ==>', err);
            }).then(res => {
                // 页面跳转成功
                // console.log('place_order to order_success success ==>', res);
            }, err => {
                // 页面跳转失败
                console.log('place_order to order_success fail ==>', err);
            }).finally(() => {
                // 删除存储的信息
                wx.removeStorageSync('recycleAddress');
                wx.removeStorageSync('recycleType');
                wx.removeStorageSync('placeInfo');
            });
        }
    },
    /**
     * 显示预估价格的说明
     */
    onShowPriceExplain() {
        this.$showMsg('价格仅供参考，实际以上门回收价格为准');
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 获取回收订单必要信息
        this.getRecycleInfo();
        // 获取订单时间、备注等信息
        this.getPlaceInfo();
        wx.setNavigationBarTitle({
          title: this.data.orderType,
        });
        // 获取当前小时数
        this.setData({
            nowHour: new Date().getHours()
        });
        this.dealCallTimeList();
        if(this.data.orderType === '公益赠送') {
            this.setData({
                orderMoney: 0
            });
        }
    },
    /**
     * 显示消息提示
     * @param {String} msg 消息体
     * @param {String} type 提示类型[loading|success|error|none]
     */
    $showMsg(msg, type = 'none') {
        wx.showToast({
          title: msg,
          icon: type
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // console.log('place unload');
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})